package com.emm.yixun.jobs;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.emm.yixun.common.model.enums.MerchantEnum;
import com.emm.yixun.system.service.pmo.PmoDynamicDataServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.common.enums.ResponseEnums;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectPmo;
import com.emm.yixun.common.model.dto.PmoLogDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectPmoDto;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.MD5;
import com.emm.yixun.common.utils.RequestUtil;
import com.emm.yixun.common.utils.ResponseBody;
import com.emm.yixun.estate.service.ProjectPmoServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.jobs.config.PmoConfig;
import com.emm.yixun.system.service.PmoLogServiceFacade;

@Component
public class SendPmoDynamiSalesDataJob {

	private static Logger logger = LoggerFactory.getLogger(SendPmoDynamiSalesDataJob.class);

	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private ProjectPmoServiceFacade projectPmoServiceFacade;

	@Autowired
	private PmoConfig pmoConfig;

	@Autowired
	private PmoLogServiceFacade pmoLogServiceFacade;
	@Autowired
	private PmoDynamicDataServiceFacade pmoDynamicDataServiceFacade;
	//绿城专属,推送PMO统计数据
	@Scheduled(cron = "0 0 23 * * ?")
	public void taskRun() {
		Date now = new Date();
		String month = DateUtils.DateToString(now, DateStyle.YYYYMM);
		ProjectDto projectDto = new ProjectDto();
		projectDto.setMerchantId(Long.valueOf(MerchantEnum.GREEN_TOWN.getNo()));
		ResponseList<Project> responseList = projectServiceFacade.findByDto(projectDto);
		if (responseList.isSuccess() && responseList != null && !responseList.getEntity().isEmpty()) {
			try{
				for (Project p : responseList.getEntity()) {
					ProjectPmoDto pmoDto = new ProjectPmoDto();
					pmoDto.setProjectId(p.getId());
					ResponseList<ProjectPmo> pmoList = projectPmoServiceFacade.findByDto(pmoDto);
					if (pmoList != null && !pmoList.getEntity().isEmpty()) {
						String projectPmoCode = pmoList.getEntity().get(0).getPmoProjectCode();
						if (StringUtils.isBlank(projectPmoCode))
							continue;

						Response<LevelDynamiSalesData> response = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(projectPmoCode, month);
						//旧版本推送
						//Response<LevelDynamiSalesData> response = projectServiceFacade.quereyLevelDynamiSalesData(projectPmoCode, month);
						if (!response.isSuccess()) {
							continue;
						}

						boolean pmoPushFlag = projectServiceFacade.checkPmoPush(projectPmoCode);
						if(!pmoPushFlag){
							continue;
						}
						LevelDynamiSalesData levelDynamiSalesData = response.getEntity();
						String json = JSON.toJSONString(levelDynamiSalesData);
						String clientKey = pmoConfig.getClientKey();
						String seq = pmoConfig.getSeq();
						String digest = MD5.md5(clientKey + seq + pmoConfig.getClientPwd()).toUpperCase();
						String url = pmoConfig.getRequest_url() + "/api/v1/pmo/project-dynamic-sale/" + projectPmoCode;
						ResponseBody responseBody = RequestUtil.buildRequest(json, url, clientKey, seq, digest);
						if (!responseBody.getCode().equals("000000")) {
							logger.error("PMO动态销售数据推送错误：" + responseBody.getDesc());
						}
						PmoLogDto pmoLogDto = new PmoLogDto();
						pmoLogDto.setMerchantId(Long.valueOf(1));
						pmoLogDto.setDirection("1");
						if (responseBody.getCode().equals(ResponseEnums.RESPONSEENUMS_000000.getCode())) {// 成功
							pmoLogDto.setStatus("1");
						} else {
							pmoLogDto.setStatus("2");
						}
						pmoLogDto.setRequestParams(json);
						pmoLogDto.setDelFlag("0");
						pmoLogDto.setInterfaceName("销售动态信息");
						pmoLogDto.setReturnResult(JSON.toJSONString(responseBody));
						pmoLogServiceFacade.save(pmoLogDto);
					}
				}
			}catch(Exception ex){
				logger.error("推送PMO数据异常", ex);
			}
		}
	}

	/**
	 * 
	 * @return
	 */
	public static String getMonthFirstDay() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		SimpleDateFormat firstDay = new SimpleDateFormat(DateStyle.YYYYMMDD.getValue());
		return firstDay.format(calendar.getTime());
	}

}
